var _that
var app = getApp()
var {keepTwoDecimalFull} = require('../../utils/util')
var _cartype

function carInit(target, cartype = 'bread') {
  _that = target
  _cartype = cartype
  _that.setData({
    showCartCnt: false,
    showCart: false,
    carscrollhgt: 0,
    goodslist: {},
    flyerStyle: {}
  })

  loadCarData()
}

function showDetail() {
  if (_that.data.totalcount <= 0) {
    return
  }
  _that.setData({
    showCart: true
  })
}

function closeDetail() {
  _that.setData({
    showCartCnt: false
  })
  setTimeout(() => {
    _that.setData({
      showCart: false
    })
  }, 300)
}

function toggleDetail () {
  if (_that.data.showCart) {
    closeDetail()
  } else {
    showDetail()
  }
}

function update() {

}

function submitOrder(orderinfo) {
  wx.navigateTo({
    url: '../neworder/neworder?type=' + _cartype,
  })
}

function handleCount(e) {
  var options, goodsid
  if (e.currentTarget) {
    options = parseInt(e.currentTarget.dataset.options)
    goodsid = e.currentTarget.dataset.goodsid
  }
  else {
    options = e.options
    goodsid = e.goodsid
  }

  var goodslist = _that.data.goodslist
  var totalcount = parseInt(_that.data.totalcount)
  var totalprice = parseFloat(_that.data.totalprice)
  if (options === '1') {
    totalcount += 1
    totalprice += 19.99
    goodslist.push({
      name: '甜杏软欧',
      price: '19.99',
      count: '1',
      img: '../imgs/index/goods6.jpg'
    })
  }
  else {
    if (totalcount - 1 < 0) {

    }
    else {
      totalcount -= 1
      totalprice -= 19.99
      goodslist.pop()
    }
  }
  totalprice = keepTwoDecimalFull(totalprice)
  _that.setData({
    totalcount: totalcount,
    totalprice: totalprice,
    goodslist: goodslist
  })
  if (totalcount === 0) {
    _that.setData({
      showCart: false
    })
  }
}

module.exports = {
  init: carInit,
  showCar: showDetail,
  closeCar: closeDetail,
  toggleCar: toggleDetail,
  update: update,
  submitOrder: submitOrder,
  handleCount: handleCount
}

//------以下方法不外调
function loadCarData() {
  var totalcount = 0
  var totalprice = 0.00
  var goodslist = []
  if (_that.data.count) {
    count = parseInt(_that.data.count)
  }
  if (_that.data.totalprice) {
    count = parseFloat(_that.data.totalprice)
  }
  _that.setData({
    totalcount: totalcount,
    totalprice: totalprice,
    goodslist: goodslist
  })
}
